package com.zglc.ms.shop.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zglc.ms.shop.dao.AddressDao;
import com.zglc.ms.shop.model.Region;
import com.zglc.ms.shop.model.UserAddress;

@Service
public class AddressService {

	private Map<Integer, String> regionMap = new HashMap<>();

	@Autowired
	private AddressDao addressDao;

	private void initRegionMap() {
		if (CollectionUtils.isEmpty(regionMap)) {
			List<Region> list = addressDao.getAll();
			for (Region region : list) {
				regionMap.put(region.getId(), region.getName());
			}
		}
	}

	public List<Region> getRegions() {
		List<Region> list = addressDao.getAll();
		return list;
	}

	public List<UserAddress> getAddress(int userId) {
		initRegionMap();
		List<UserAddress> list = addressDao.getAddress(userId);
		if (CollectionUtils.isEmpty(list)) {
			return list;
		}

		for (UserAddress userAddress : list) {
			userAddress.setPca(regionMap.get(userAddress.getProvId()) + " " + regionMap.get(userAddress.getCityId())
				+ " " + regionMap.get(userAddress.getAreaId()));
			userAddress.setRemark(regionMap.get(userAddress.getProvId()) + regionMap.get(userAddress.getCityId())
			+ regionMap.get(userAddress.getAreaId()) + userAddress.getDetail());
		}
		
		return list;
	}

	public UserAddress getAddressById(int id) {
		UserAddress userAddress = addressDao.getAddressById(id);
		if (userAddress == null) {
			return null;
		}

		initRegionMap();
		userAddress.setRemark(regionMap.get(userAddress.getProvId()) + regionMap.get(userAddress.getCityId())
				+ regionMap.get(userAddress.getAreaId()) + userAddress.getDetail());
		return userAddress;
	}

	public UserAddress getLastestAddress(int userId) {
		UserAddress userAddress = addressDao.getLastestAddress(userId);
		if (userAddress == null) {
			return null;
		}

		initRegionMap();
		userAddress.setRemark(regionMap.get(userAddress.getProvId()) + regionMap.get(userAddress.getCityId())
				+ regionMap.get(userAddress.getAreaId()) + userAddress.getDetail());
		return userAddress;
	}

	public boolean isExistUserAddress(int userAddressId, int userId) {
		return addressDao.isExist(userAddressId, userId);
	}

	public void del(int userAddressId, int userId) {
		addressDao.del(userAddressId, userId);
	}

	public boolean update(int id, int provId, int cityId, int areaId, String detail, String contact, String phone) {
		boolean isSave = addressDao.update(id, provId, cityId, areaId, detail, contact, phone);
		return isSave;
	}

	public Integer getAddressId(int userId, int provId, int cityId, int areaId, String detail, String contact,
			String phone) {
		return addressDao.getAddressId(userId, provId, cityId, areaId, detail, contact, phone);
	}

	public Integer save(int userId, int provId, int cityId, int areaId, String detail, String contact, String phone) {
		Integer id = addressDao.getAddressId(userId, provId, cityId, areaId, detail, contact, phone);
		if (id != null && id > 0) {
			return id;
		}

		id = addressDao.save(userId, provId, cityId, areaId, detail, contact, phone);
		return id;
	}

	public static class MenuTree {
		private StringBuffer jsonStr = new StringBuffer();
		private List<Region> regions;

		public MenuTree(List<Region> regions) {
			this.regions = regions;
		}

		public JSONArray buildJsonTree() {
			JSONArray jarray = new JSONArray();
			for (Region node : regions) {
				if (node.getpId() == 1) {
					JSONObject p1Json = new JSONObject();
					p1Json.put("id", node.getId());
					p1Json.put("name", node.getName());
					jarray.add(p1Json);
					buildJson(node, p1Json);
				}
			}

			return jarray;
		}

		public String buildTree() {
			jsonStr.append("[");
			for (Region node : regions) {
				if (node.getpId() == 1) {
					jsonStr.append("{").append("'id':").append(node.getId()).append(",").append("'name':'")
							.append(node.getName()).append("'");
					build(node);
					jsonStr.append("},");
				}
			}

			return jsonStr.substring(0, jsonStr.length() - 2) + "]";
		}

		private void build(Region node) {
			List<Region> children = getChildren(node);
			if (!children.isEmpty()) {
				jsonStr.append(", 'child':[");
				int length = children.size();
				int i = 0;
				for (Region child : children) {
					i++;
					jsonStr.append("{").append("'id':").append(child.getId()).append(",").append("'name':'")
							.append(child.getName()).append("'");
					build(child);

					if (length == i) {
						jsonStr.append("}");
					} else {
						jsonStr.append("}, ");
					}
				}

				jsonStr.append("]");
			}
		}

		private void buildJson(Region node, JSONObject chJson) {
			List<Region> children = getChildren(node);
			if (!children.isEmpty()) {
				JSONArray jarray = new JSONArray();
				for (Region child : children) {
					JSONObject cJson = new JSONObject();
					cJson.put("id", child.getId());
					cJson.put("name", child.getName());
					jarray.add(cJson);
					buildJson(child, cJson);
				}

				chJson.put("child", jarray);
			}
		}

		private List<Region> getChildren(Region node) {
			List<Region> children = new ArrayList<>();
			Integer id = node.getId();
			for (Region child : regions) {
				if (id == child.getpId() && id != child.getId()) {
					children.add(child);
				}
			}

			return children;
		}
	}

}